# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : config.py
# Time       ：2021/8/28 16:10
# Author     ：王洪磊
# Email      ： wang_hl007@163.com
# Description：
"""

import configparser
import os
import threading

ConfigParser = configparser.ConfigParser


class Config(ConfigParser):
    # TODO
    #  设置两个文件，一个是初始的设置文件，一个是用户设置文件，
    #  首先检索用户设置文件中没有的再去初始文件中搜索，
    #  设置更新用户设置文件

    _instance_lock = threading.Lock()

    def __init__(self, path):
        self.path = path
        super(Config, self).__init__()
        self.read(path, encoding='utf-8')

    # single mode，  the config file must be control by the only one
    def __new__(cls, *arg, **kwargs):
        if not hasattr(Config, "_instance"):
            with Config._instance_lock:
                if not hasattr(Config, "_instance"):
                    Config._instance = object.__new__(cls)
        return Config._instance

    def get_sql(self):
        if 'sql' in self.sections():
            user = self.get('sql', 'user')
            password = self.get('sql', 'password')
            host = self.get('sql', 'host')
            db = self.get('sql', 'db')
            port = self.get('sql', 'port')
            return user, password, host, db, port

    def save_config(self, section, key_name, value):

        if self.has_section(section) and self.has_option(section, key_name):
            self.set(section, key_name, str(value))
            with open(self.path, "w+") as f:
                # auto close file if file don`t work
                self.write(f)

    def get_option(self, section, option):

        try:
            return self.get(section, option)
        except Exception:
            return None

    def add_options(self, section, options: dict):
        # 添加
        if not self.has_section(section):
            self.add_section(section)
        for key_name in options.keys():
            self.set(section, key_name, str(options.get(key_name)))


def get_config():
    path = r'D:\云空间\Git\微震分析系统\config\config.ini'
    config = Config(path)
    return config


def main():

    config = get_config()

    value = config.get_sql()
    print(value)


if __name__ == "__main__":
    main()

